package com.coocaa.ops.admin.v1.audit.service.impl;


import com.coocaa.ops.admin.async.log.service.LogRecordServiceImpl;
import com.coocaa.ops.admin.base.annotation.AuditOps;
import com.coocaa.ops.admin.v1.audit.AuditUtil;
import com.coocaa.ops.admin.v1.audit.enums.AuditReturnValEnums;
import com.coocaa.ops.admin.v1.audit.model.CheckInfoModel;
import com.coocaa.ops.admin.v1.audit.model.ExecutionTaskModel;
import com.coocaa.ops.admin.v1.audit.service.AuditTaskProviderManager;
import com.coocaa.ops.admin.v1.audit.service.IAuditTaskService;
import com.coocaa.ops.admin.v1.auth.sys.biz.impl.SysUserBizImpl;
import com.coocaa.ops.admin.v1.timedtask.job.TimelyShelvesQuartzJob;
import com.coocaa.ops.admin.v1.timedtask.job.impl.MyQuartzJobServiceImpl;
import com.coocaa.ops.admin.v1.timedtask.provider.impl.TimedTaskProviderImpl;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.model.R;
import com.coocaa.ops.common.core.base.model.ResourceBaseModel;
import com.coocaa.ops.common.core.base.model.SimpleSysUserInfo;
import com.coocaa.ops.common.core.biz.audit.entity.AuditTaskInfoEntity;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author bijiahao
 * @date : 2018/6/15.
 * @description: 审核前校验-审核-撤销审核-上架操作服务实现
 * 见配置 @link{audit/audit-task-provider-bean.xml}
 */
@Service
public class AuditTaskServiceImpl implements IAuditTaskService {
    @Autowired
    private TimedTaskProviderImpl timedTaskProvider;
    @Autowired
    private MyQuartzJobServiceImpl myQuartzJobService;
    //    @Autowired
//    private SendEmailServiceImpl sendEmailService;
    @Autowired
    private LogRecordServiceImpl logRecordService;
    @Autowired
    private SysUserBizImpl sysUserBiz;
    @Autowired
    private AuditTaskProviderManager auditTaskProviderManager;


    /**
     * 执行任务-审核操作
     *
     * @param executionTaskModel
     * @param userInfo
     * @return
     */
    @AuditOps
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> auditTask(ExecutionTaskModel executionTaskModel, SimpleSysUserInfo userInfo) {
        CheckInfoModel checkModel = checkBeforeAudit(executionTaskModel);
        if (null != checkModel && checkModel.isResult()) {
            return R.fail("Failed verification：" + checkModel.getMsg());
        }
        long startTime = System.currentTimeMillis();
        //资源ID
        Integer resourceId = executionTaskModel.getId();
        //资源版本
        Integer resourceVersion = executionTaskModel.getVersion();
        //资源类型
        String resourceType = executionTaskModel.getType();
        //审核状态-【审核通过-状态4,审核不通过-状态5】
        Integer auditFlag = executionTaskModel.getAuditFlag();

        AuditTaskInfoEntity auditTaskInfo = AuditUtil.getTaskByIdAndVersionAndType(resourceId, resourceVersion, resourceType);
        if (null == auditTaskInfo) {
            Map opParams = InstanceUtil.newHashMap(3);
            opParams.put("resourceId", resourceId);
            opParams.put("resourceVersion", resourceVersion);
            opParams.put("resourceType", resourceType);
            throw new BusinessException(opParams, "The corresponding audit task information does not exist");
        }
        //处理定时任务
        Integer handleTimedTaskReturnVal = handleTimedTask(auditTaskInfo, auditFlag);
        //step1：修改任务表审核状态和审核意见
        if (handleTimedTaskReturnVal == AuditReturnValEnums.AUDIT_TIMED_TASK_READY_TO_EXEC.getCode()) {
            //定时任务处理返回结果【如果是状态7-审核通过未上线】赋值auditFlag=7
            auditFlag = AuditReturnValEnums.AUDIT_TIMED_TASK_READY_TO_EXEC.getCode();
        }
        Integer userId = userInfo.getUserId();
        //处理保存审核任务信息
        this.handleSaveAuditTaskInfo(auditTaskInfo, auditFlag, executionTaskModel.getAuditDesc(), userId);
        //设置审核状态
        executionTaskModel.setAuditFlag(auditFlag);
        //根据资源类型【resourceType】处理不同的审核逻辑
        auditTaskProviderManager.getAuditTaskProvider(resourceType).auditTask(executionTaskModel, userId);
        //发送邮件
        sendEmailForAuditTask(auditTaskInfo, userId, auditFlag);
        //日志切面
        long endTime = System.currentTimeMillis();
        logRecordService.logOpRecord(executionTaskModel, userInfo, endTime - startTime);
        //返回信息
        ExecutionTaskModel returnModel = new ExecutionTaskModel();
        returnModel.setId(resourceId);
        returnModel.setVersion(resourceVersion);
        returnModel.setType(resourceType);
        returnModel.setAuditFlag(auditFlag);
        return R.ok().data(returnModel);
    }

    /**
     * 上架操作
     *
     * @param resourceBaseModel
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void putShelves(ResourceBaseModel resourceBaseModel, Integer userId) {
        auditTaskProviderManager.getAuditTaskProvider(resourceBaseModel.getType()).putShelves(resourceBaseModel, userId);
    }

    /**
     * 撤销审核
     *
     * @param resourceBaseModel
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void revokedAudit(ResourceBaseModel resourceBaseModel, Integer userId) {
        //资源类型
        String resourceType = resourceBaseModel.getType();
        AuditTaskInfoEntity taskInfo = AuditUtil.getTaskByIdAndVersionAndType(resourceBaseModel.getId(), resourceBaseModel.getVersion(), resourceType);
        if (null != taskInfo) {
            AuditUtil.logicDelByIdAndVersionAndType(resourceBaseModel.getId(), resourceBaseModel.getVersion(), resourceType);
        }
        auditTaskProviderManager.getAuditTaskProvider(resourceType).revokedAudit(resourceBaseModel, userId);

        //发送邮件
//        String auditer = sysUserBiz.getLoginName(userId);
//        String createderEmail = sysUserBiz.getEmailByUserId(taskInfo.getCreator());
//        List<String> emails = InstanceUtil.newArrayList();
//        emails.add(createderEmail);
//        sendEmailService.sentEmailForAuditTask("[6.X运营平台]提醒：" + EmailInfoBuilder.getResourceTypeName(resourceType) + "[" + taskInfo.getTaskName() + "]已经撤销审核",
//                "送审任务：[" + taskInfo.getTaskName() + "][" + EmailInfoBuilder.getResourceTypeName(resourceType) + "]已经撤销审核，撤销人：" + auditer + "，撤销时间：[" +
//                        new Date() + "]", emails);
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/
    private CheckInfoModel checkBeforeAudit(ResourceBaseModel resourceBaseModel) {
        return auditTaskProviderManager.getAuditTaskProvider(resourceBaseModel.getType()).checkBeforeAudit(resourceBaseModel);
    }


    /**
     * 处理保存审核任务信息
     *
     * @param auditTaskInfo
     * @param auditFlag
     * @param auditDesc
     * @param userId
     */
    private void handleSaveAuditTaskInfo(AuditTaskInfoEntity auditTaskInfo, Integer auditFlag, String auditDesc, Integer userId) {
        //审核人
        auditTaskInfo.setCurrentOperator(userId);
        //该任务走完审核流程：即结束
        auditTaskInfo.setTaskFlag(3);
        //审核结论
        auditTaskInfo.setAuditFlag(auditFlag);
        //审核意见
        auditTaskInfo.setAuditDesc(auditDesc);
        //更新审核任务信息
        AuditUtil.updateById(auditTaskInfo);
        //保存历史审核表记录
        AuditUtil.saveAuditTaskInfoHistory(auditTaskInfo);
    }


    /**
     * 处理定时任务
     *
     * @param entity
     * @param auditFlag
     * @return
     */
    private Integer handleTimedTask(AuditTaskInfoEntity entity, Integer auditFlag) {
        if (ResourceStatusEnums.AUDITED_NOT_PASS.getStatus() == auditFlag) {
            //审核不通过-【状态5】
            return AuditReturnValEnums.AUDIT_NOT_PASS.getCode();
        }
        //如果审核通过未上线-【状态7】
        TimedTaskInfoEntity timedTaskInfo = timedTaskProvider.queryTimedTaskForTimelyShelves(entity.getResourceType(), entity.getResourceId(), entity.getResourceVersion());
        if (null == timedTaskInfo) {
            return AuditReturnValEnums.AUDIT_TIMED_TASK_NOT_EXSIST.getCode();
        }
        long taskReleaseTime = timedTaskInfo.getReleaseTime().getTime();
        long currentTime = System.currentTimeMillis();
        if (auditFlag == ResourceStatusEnums.ON_LINE.getStatus() && taskReleaseTime < currentTime) {
            //更新定时任务状态
            timedTaskProvider.updateTimedTaskStatusById(timedTaskInfo.getId(), ResourceStatusEnums.ON_LINE.getStatus());
            return AuditReturnValEnums.AUDIT_TIMED_TASK_HAS_EXPIRED.getCode();
        }
        //将定时任务 添加进任务池
        myQuartzJobService.addJobForTimelyShelves(timedTaskInfo, TimelyShelvesQuartzJob.class);
        timedTaskProvider.updateTimedTaskStatusById(timedTaskInfo.getId(), ResourceStatusEnums.AUDITED_NOT_ON_LINE.getStatus());
        return AuditReturnValEnums.AUDIT_TIMED_TASK_READY_TO_EXEC.getCode();
    }


    /**
     * 发送邮件
     *
     * @param auditTaskInfo
     * @param userId
     * @param auditFlag
     */
    private void sendEmailForAuditTask(AuditTaskInfoEntity auditTaskInfo, Integer userId, Integer auditFlag) {
//        if (!SystemProperties.SystemConstants.ENABLE_SEND_EMAIL) {
//            return;
//        }
        //审核人名字
//        String auditer = sysUserBiz.getLoginName(userId);
//        String createderEmail = sysUserBiz.getEmailByUserId(auditTaskInfo.getCreator());
//        List<String> emails = InstanceUtil.newArrayList();
//        emails.add(createderEmail);
//        String conclusionChes = null;
//        if (auditFlag == ResourceStatusEnums.ON_LINE.getStatus()) {
//            //审核通过上线中
//            conclusionChes = ResourceStatusEnums.ON_LINE.getDesc();
//        } else if (auditFlag == ResourceStatusEnums.AUDITED_NOT_PASS.getStatus()) {
//            //审核不通过
//            conclusionChes = ResourceStatusEnums.AUDITED_NOT_PASS.getDesc();
//        } else if (auditFlag == ResourceStatusEnums.AUDITED_NOT_ON_LINE.getStatus()) {
//            //审核通未上线
//            conclusionChes = ResourceStatusEnums.AUDITED_NOT_ON_LINE.getDesc();
//        }
//        sendEmailService.sentEmailForAuditTask("[6.X运营平台]提醒：" + EmailInfoBuilder.getResourceTypeName(auditTaskInfo.getResourceType()) + "[" + auditTaskInfo.getTaskName() + "]已经审核[" + conclusionChes + "]",
//                "送审任务：[" + auditTaskInfo.getTaskName() + "][" + EmailInfoBuilder.getResourceTypeName(auditTaskInfo.getResourceType()) + "]已经审核完成，审核人：" + auditer + "，审核时间：[" +
//                        new Date() + "]，审核意见：" + auditTaskInfo.getAuditDesc(), emails);
    }

}
